package com.mk.admin.controller;

import com.alibaba.fastjson2.JSONObject;
import com.mk.admin.model.ResultDto;
import com.mk.admin.model.vo.FileVo;
import com.mk.admin.util.DateTool;
import com.mk.admin.util.HttpTool;
import com.mk.admin.util.IOTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;


@RestController
@RequestMapping
@Api(tags = "上传图片")
public class UploadController {
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @PostMapping("/upload/{filePath}")
    @ApiOperation("文件上传")
    public ResultDto upload(@RequestParam("file") MultipartFile file, @PathVariable String filePath) {
        if (file != null) {
//            获取文件名
            String fileName = file.getOriginalFilename();
            fileName = DateTool.nullToNowDate("yyyyMMddhhmmssSSS") + "---" + fileName;
            String month = "";
            try {
                String projectPath = ResourceUtils.getURL("classpath:").getPath();
                String path = projectPath.split("/target/")[0] + "/src/main/resources/static/img/";
                if (!"".equals(uploadFolder)) {
                    path = uploadFolder;//发布到服务器需要这个路径
                }
//                每月新创建一个文件夹，如果不需要则注释下面这行即可
//                month = "/" + DateTool.nullToNowDate("yyyyMM");
                path += filePath + month;


//直接将前端传递过来的文件保存到资源文件
                file.transferTo(IOTool.file(path, fileName));
//                正式发布时，下面代码就不需要了
                if ("".equals(uploadFolder)) {
                    //复制图片
                    String resourcePath = path + "/" + fileName;
                    String newPath = projectPath + "/static/img/" + filePath + month;

                    String targetPath = newPath + "/" + fileName;
//// 将资源文件复制到target里面
                    IOTool.createFile(newPath);
                    IOTool.copyFile(resourcePath, targetPath);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ResultDto.data("/img/" + filePath + month + "/" + fileName);
        }
        return null;
    }

    @PostMapping("/pdf")
    @ApiOperation("地址转成PDF")
    public ResultDto pdf(@RequestBody FileVo vo) {
        JSONObject jsonObject = HttpTool.pdf(vo.getPicUrl());
        Object result = jsonObject.get("result");
//        if (result != null) {
//            return ResultDto.data(result);
//        }
//        return ResultDto.data(jsonObject);
//        Object result = jsonObject.get("result");
        String fileName = "";
        if (result != null && !"".equals(result)) {
            JSONObject jsonObject1 = JSONObject.parseObject(JSONObject.toJSONString(result));
//            String base64 = jsonObject1.getString("base64");
            String base64Data =jsonObject1.getString("base64");
//            String base64Data = base64.replace("\n", "");
            String outputPath = ""; // 例如： "C:/files/image.png"

            try {
                String projectPath = ResourceUtils.getURL("classpath:").getPath();
                String path = projectPath.split("/target/")[0] + "/src/main/resources/static/file/";
                if (!"".equals(uploadFolder)) {
                    path = uploadFolder;//发布到服务器需要这个路径
                }
                fileName = DateTool.nullToNowDate("yyyyMMddhhmmssSSS") + "---" + vo.getPatId() + ".pdf";

                boolean success = saveBase64ToFile(base64Data, path + fileName);
                if (success) {
                    System.out.println("文件保存成功: " + path + fileName);
                }
                if ("".equals(uploadFolder)) {
                    //复制图片
                    String resourcePath = path + "/" + fileName;
                    String newPath = projectPath + "/static/file/";

                    String targetPath = newPath + "/" + fileName;
//// 将资源文件复制到target里面
                    IOTool.createFile(newPath);
                    IOTool.copyFile(resourcePath, targetPath);
                }
            } catch (IOException e) {
                System.err.println("保存失败: " + e.getMessage());
            }
        }
        return ResultDto.data("/file/" + fileName);
    }

    /**
     * 将Base64字符串保存为文件
     *
     * @param base64Data 完整的Base64字符串（可包含data URI前缀）
     * @param outputPath 文件保存路径（包含文件名和扩展名）
     * @return 是否保存成功
     * @throws IOException 文件操作异常
     */
    public static boolean saveBase64ToFile(String base64Data, String outputPath) throws IOException {
        // 1. 清理Base64字符串（移除data URI前缀）
        String cleanedBase64 = cleanBase64Data(base64Data);

        // 2. Base64解码
        byte[] decodedBytes = Base64.getDecoder().decode(cleanedBase64);

        // 3. 创建父目录（如果不存在）
        File outputFile = new File(outputPath);
        File parentDir = outputFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }

        // 4. 写入文件
        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
            fos.write(decodedBytes);
        }

        return true;
    }

    /**
     * 清理Base64字符串（移除data URI前缀）
     *
     * @param base64Data 原始Base64字符串
     * @return 纯净的Base64编码数据
     */
    private static String cleanBase64Data(String base64Data) {
        // 如果包含常见前缀（如：data:image/png;base64,）
        if (base64Data.contains("base64,")) {
            return base64Data.split("base64,")[1];
        }
        return base64Data;
    }
}
